package com.cema.manage.project.util;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.Date;
import java.util.Map;
import java.util.concurrent.TimeUnit;

public class HttpUtil {

    public static String sendGet(String url, String charset) {
        String result = "";
        BufferedReader in = null;
        try {
            URL realUrl = new URL(url);
            URLConnection connection = realUrl.openConnection();
            connection.setRequestProperty("accept", "*/*");
            connection.setRequestProperty("connection", "Keep-Alive");
            connection.setRequestProperty("user-agent",
                    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            connection.connect();
            in = new BufferedReader(new InputStreamReader(
                    connection.getInputStream(), charset));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            System.out.println("发送GET请求出现异常！" + e);
            e.printStackTrace();
        } finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (Exception e2) {
                e2.printStackTrace();
            }
        }
        return result;
    }

    public static String sendPostUrl(String url, String param, String charset) {
        PrintWriter out = null;
        BufferedReader in = null;
        String result = "";
        try {
            URL realUrl = new URL(url);
            URLConnection conn = realUrl.openConnection();
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("user-agent",
                    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            conn.setDoOutput(true);
            conn.setDoInput(true);
            out = new PrintWriter(conn.getOutputStream());
            out.print(param);
            out.flush();
            in = new BufferedReader(new InputStreamReader(
                    conn.getInputStream(), charset));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            System.out.println("发送 POST 请求出现异常！" + e);
            e.printStackTrace();
        } finally {
            try {
                if (out != null) {
                    out.close();
                }
                if (in != null) {
                    in.close();
                }
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
        return result;
    }

    @SuppressWarnings("deprecation")
    public static String sendPost(String url, Map<String, String> param,
                                  String charset) {
        StringBuffer buffer = new StringBuffer();
        if (param != null && !param.isEmpty()) {
            for (Map.Entry<String, String> entry : param.entrySet()) {
                buffer.append(entry.getKey()).append("=")
                        .append(URLEncoder.encode(entry.getValue()))
                        .append("&");
            }
        }
        buffer.deleteCharAt(buffer.length() - 1);
        PrintWriter out = null;
        BufferedReader in = null;
        String result = "";
        try {
            URL realUrl = new URL(url);
            URLConnection conn = realUrl.openConnection();
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded; charset=utf-8");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("user-agent",
                    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            conn.setDoOutput(true);
            conn.setDoInput(true);
            out = new PrintWriter(conn.getOutputStream());
            out.print(buffer);
            out.flush();
            in = new BufferedReader(new InputStreamReader(
                    conn.getInputStream(), charset));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            System.out.println("发送 POST 请求出现异常！" + e);
            e.printStackTrace();
        } finally {
            try {
                if (out != null) {
                    out.close();
                }
                if (in != null) {
                    in.close();
                }
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
        return result;
    }

    public static void main(String[] args) {
        DateTime dateTime = DateUtil.offsetDay(new Date(), 7);
        Long time = (dateTime.getTime()-(System.currentTimeMillis()+11720000));
        ///convertTime(time);
       String fromatTiem = DateUtil.format(new Date(time),DateUtils.DATE_TIME_PATTERN);
       System.out.println(dateTime);
    }

    public static void convertTime(long timeInMillis) {
        long days = TimeUnit.MILLISECONDS.toDays(timeInMillis);
        long hours = TimeUnit.MILLISECONDS.toHours(timeInMillis) % 24;
        long minutes = TimeUnit.MILLISECONDS.toMinutes(timeInMillis) % 60;
        long seconds = TimeUnit.MILLISECONDS.toSeconds(timeInMillis) % 60;

        System.out.println(timeInMillis + " milliseconds is");
        System.out.println(days + " days,");
        System.out.println(hours + " hours,");
        System.out.println(minutes + " minutes, and");
        System.out.println(seconds + " seconds.");
    }

//public static void login(String code) {
//		//自定义的类，就两个参数，int类型处理是否成功，Object类型存放放回的数据
//		// ReturnValue ret = new ReturnValue();
//		//第一步请求的地址，appid和secret替换成自己申请下来的即可，code就是手机获取到的参数
//		String url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + "wx8037dbef1274e71e&secret=3637cdac99bcbe2273ef821551332db0&code=" + code + "&grant_type=authorization_code";
//		//使用http请求数据，其中，HttpUtil是自己的辅助类，代码会放到后面
//		String result = HttpUtil.sendGet(url, "utf-8");
//		//我使用的fastjson，可以根据自己使用的jar包调整数据获取格式
//		// JSONObject resultJson = JSONObject.parseObject(result);
//		cn.hutool.json.JSONObject resultJson = JSONUtil.parseObj(result);
//		System.out.println(result);
//		//处理不正确的code情况，我只判断了400029，如果有完整微信错误字典，可以走框架流程
//		if (resultJson.containsKey("errcode") && resultJson.getInt("errcode") == 40029) {
////            ret.setResult(ReturnValue.FAIL);
////            ret.setData("code不合法");
////            pw.write(JSON.toJSONString(ret));
//			System.out.println("code不合法");
//			return;
//		}
//		if (resultJson.containsKey("access_token")) {
//			//下一步请求需要使用的access_token
//			String access_token = resultJson.getStr("access_token");
//			//该APP下使用微信登录获取到的唯一值
//			String openid = resultJson.getStr("openid");
//			String unionid = resultJson.getStr("unionid");
//			//使用两个参数请求用户信息
//			String url2 = "https://api.weixin.qq.com/sns/userinfo?access_token=" + access_token + "&openid=" + openid;
//			//userInfo就是需要的数据，为了方便比对，提供下我获取到的数据
//			//{"openid":"oHNVDwA8k3H2VQ3mHbXcplVmqm_U","nickname":"昵称改了下","sex":0,"language":"zh_CN","city":"","province":"","country":"CN","headimgurl":"http:\/\/wx.qlogo.cn\/mmopen\/80xzo4yia4MU5IKoUgylvFfRT1QMoVIdlZWs1icEVo3Klkknvy3MOJZuqbetdnqEw1Oibweg7jxBJT3DImlulVf5PYktSUx1QM7\/0","privilege":[],"unionid":"oJT7XwLrV90jbhO9BJSPmMkQ5-8I"}
//			//各个参数的含义可以参见文档。获取到参数之后，根据自己的业务需要选择即可
//			String userInfo = HttpUtil.sendGet(url2, "utf-8");
//			System.out.println(userInfo);
////            ret.setResult(ReturnValue.SUCCESS);
////            ret.setData(userInfo);
////            pw.write(JSON.toJSONString(ret));
//		}
//	}
}